using System;
using System.Xml;
using Raccoom.Xml;

using umbraco.cms.businesslogic.web;

namespace umbracoRss.BusinessLogic
{
	/// <summary>
	/// Summary description for Generator.
	/// </summary>
	internal class Generator
	{
		private Generator()
		{
		}

		public static bool GenerateFromPath(int ParentId, string Path, Document documentObject) 
		{
			Path = Path + ",";
			bool generated = false;
			foreach(RssInstance instance in RssInstance.GetAll()) 
			{
                // Test for filters (only generate when document type is empty or matching the alias of the newly published doc)
                if (instance.DocumentTypeAlias == "" || instance.DocumentTypeAlias == documentObject.ContentType.Alias) {
                    if (instance.FullPath && Path.IndexOf("," + instance.DocumentId.ToString() + ",") > -1) {
                        Generator.Generate(instance.Id);
                        generated = true;
                    } else if (!instance.FullPath && ParentId == instance.DocumentId) {
                        Generator.Generate(instance.Id);
                        generated = true;
                    }
                }
			}

			return generated;
		}

		public static void Generate(int Id) 
		{
			// Get instance
			RssInstance instance = new RssInstance(Id);
			RssChannel channel = new RssChannel();

			// Populate metadata
			channel.Title = instance.Title;
			channel.Ttl = instance.TTL;
			channel.PubDate = System.DateTime.Now;
			channel.Copyright = instance.Copyright;
			channel.Link = "http://" + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + umbraco.library.NiceUrl(instance.DocumentId);

			// set culture
			if (umbraco.library.GetCurrentDomains(instance.DocumentId) != null) 
			{
				channel.Language = System.Globalization.CultureInfo.CreateSpecificCulture(umbraco.library.GetCurrentDomains(instance.DocumentId)[0].Language.CultureAlias);
			}
			
			if (instance.Items != null)
                for(int i=0;i<instance.Items.Length;i++)
					channel.Items.Add(instance.Items[i]);
			

            channel.Save(System.Web.HttpContext.Current.Server.MapPath(umbraco.GlobalSettings.StorageDirectory + "/rss/" + instance.Url));
			
		}
	}
}
